<?php
# LemurCMS by Alec Gorge
#
#     This file contains the PHP functions used throught the CMS.
#
# updated: Feb. 6, 2009

# FROM http://us2.php.net/manual/en/function.array-search.php#88710
function search_within_array ($needle, $haystack, $inverse = false, $limit = 1) {
   
    # Settings
    $path = array ();
    $count = 0;
   
    # Check if inverse
    if ($inverse == true)
        $haystack = array_reverse ($haystack, true);
       
    # Loop
    foreach ($haystack as $key => $value) {

        # Check for return
        if ($count > 0 && $count == $limit)   
            return $path;
       
        # Check for val
        if ($value === $needle) {
           
		   var_dump($key);
            # Add to path
            $path[] = $key;
           
            # Count
            $count++;
           
        } else if (is_array ($value)) {
           
            # Fetch subs
            $sub = search_within_array ($needle, $value, $inverse, $limit);
           
            # Check if there are subs
            if (count ($sub) > 0) {
               
                # Add to path
                $path[$key] = $sub;
               
                # Add to count
                $count += count ($sub);
            }
        }
    }
   
    return $path;
}

class themeManager extends functions {
	public $childLookup, $childLookup1, $childLookup2, $idLookup1, $idLookup1clean, $idLookup2clean, $idLookup2, $idLookup = false, $idLookupClean = false, $nav_link, $r, $staticContent, $arrayNavigation, $arraySecondaryNavigation, $themeStaticContent, $navigation = false, $secondary_navigation = false, $blacklist = array();
	public function __construct ($id = "") {
		$this->id = $id;
		$this->arrayStaticContent();
	}
	public function countNavItems ($nav) {
		if($nav == 'primary') {
			if (empty($this->arrayNavigation))
				$this->arrayNavigation();
			return count($this->arrayNavigation);
		}
		elseif ($nav == 'secondary') {
			if (empty($this->arraySecondaryNavigation))
				$this->arraySecondaryNavigation();
			return count($this->arraySecondaryNavigation);
		}
	}
	public function arrayStaticContent () {
		if(!isset($GLOBALS['staticContent'])) {
			$sql = "SELECT * FROM ".DBTABLEPREFIX."content_template WHERE template = '".$this->getSetting('Theme')."' ORDER by id";
			$run = $this->db_query($sql)or die($this->db->error());
				$call_info = array_shift( debug_backtrace() );
				$code_line = $call_info['line'];
				$file = array_pop( explode('/', $call_info['file']));
			while($rec = $this->db->fetchAssoc($run)) {
				$r[$rec['name']] = array(
					'id' => $rec['id'],
					'content' => stripslashes($rec['content']),
					'name' => $rec['name'],
					'textOnly' => $rec['textOnly']
				);
			}
			$this->staticContent = $r;
			$GLOBALS['staticContent'] = $r;
		}
		return $GLOBALS['staticContent'];
	}
	public function arrayNavigation($oneline = false) {
		if(empty($this->arrayNavigation)) {
			if($oneline == false) {
				$refs = array();
				$list = array();
				$sql = "SELECT parent_id, menutitle, id FROM ".DBTABLEPREFIX."content_pages WHERE NOT secondary = 'yes' ORDER by orderingid ";
				$run = $this->db_query($sql)or die($this->db->error());
				while($data = @$this->db->fetchAssoc($run)) {
					$thisref = &$refs[ $data['id'] ];
					$thisref['id'] = $data['id'];
					$thisref['menutitle'] = $data['menutitle'];
					if ($data['parent_id'] == 0) {
						$list[$thisref['id']] = &$thisref;
					} else {
						$refs[ $data['parent_id'] ]['children'][ $thisref['id'] ] = &$thisref;
					}
					$list2[$thisref['id']] = $thisref['menutitle'];
					$list3[$thisref['id']] = $this->make_clean_url($thisref['menutitle']);
					$list4[$thisref['id']] = $data['parent_id'];
				}
				$this->arrayNavigation = $list;
				$this->idLookup1 = $list2;
				$this->idLookup1clean = $list3;
				$this->childLookup1 = $list4;
				return $list;
			}
			else {
				$sql = "SELECT * FROM ".DBTABLEPREFIX."content_pages WHERE NOT secondary = 'yes' ORDER by orderingid ";
				$run = $this->db_query($sql)or die($this->db->error());
				while($rec = $this->db->fetchAssoc($run)) {
					$return[$rec['menutitle']] = $rec['id'];	
				}
				return $return;
			}
		}
		else {
			return $this->arrayNavigation;
		}
	}
	public function arraySecondaryNavigation($oneline = false) {
		if(empty($this->arraySecondaryNavigation)) {
			if($oneline == false) {
				$refs = array();
				$list = array();
				$sql = "SELECT parent_id, menutitle, id FROM ".DBTABLEPREFIX."content_pages WHERE secondary = 'yes' ORDER by orderingid";
				$run = $this->db_query($sql)or die($this->db->error());
				while($data = @$this->db->fetchAssoc($run)) {
					$thisref = &$refs[ $data['id'] ];
					$thisref['id'] = $data['id'];
					$thisref['menutitle'] = $data['menutitle'];
					if ($data['parent_id'] == 0) {
						$list[$thisref['id']] = &$thisref;
					} else {
						$refs[ $data['parent_id'] ]['children'][ $thisref['id'] ] = &$thisref;
					}
					$list2[$thisref['id']] = $thisref['menutitle'];
					$list3[$thisref['id']] = $this->make_clean_url($thisref['menutitle']);
					$list4[$thisref['id']] = $data['parent_id'];
				}
				$this->arraySecondaryNavigation = $list;
				$this->idLookup2 = $list2;
				$this->idLookup2clean = $list3;
				$this->childLookup2 = $list4;
				return $list;
			}
			else {
				$sql = "SELECT * FROM ".DBTABLEPREFIX."content_pages WHERE secondary = 'yes' ORDER by orderingid";
				$run = $this->db_query($sql)or die($this->db->error());
				while($rec = $this->db->fetchAssoc($run)) {
					$return[$rec['menutitle']] = $rec['id'];	
				}
				return $return;
			}
		}
		else {
			return $this->arraySecondaryNavigation;
		}
	}
	public function idLookup($str, $reverse = false, $clean = false) {
		if(empty($this->arraySecondaryNavigation))
			$this->arraySecondaryNavigation();
		if(empty($this->arrayNavigation))
			$this->arrayNavigation();
		if($this->idLookup == false)
			$this->idLookup = (array)$this->idLookup1 + (array)$this->idLookup2;
		if($this->idLookupClean == false)
			$this->idLookupClean = (array)$this->idLookup1clean + (array)$this->idLookup2clean;
		if(array_key_exists($str,(array) $this->idLookupClean) && $reverse == false && $clean == true)
			return $this->idLookupClean[$str];
		elseif(array_key_exists($str, (array)$this->idLookup) && $reverse == false)
			return $this->idLookup[$str];
		elseif(in_array($str, (array) $this->idLookup) && $reverse == true && $clean == false)
			return array_search($str, $this->idLookup);
		elseif(in_array($str,(array) $this->idLookupClean) && $reverse == true && $clean == true)
			return array_search($str, $this->idLookupClean);
	}
	public function subPagesOf ($str, $a = "\n<ul class='subpagelist'>\n%s\n</ul>", $b = "\n\t<li><a href=\"%2\$s\">%1\$s</a></li>", $c = "\n\t<li>This page has no sub pages.</li>") {
		if(empty($this->arraySecondaryNavigation))
			$this->arraySecondaryNavigation();
		if(empty($this->arrayNavigation))
			$this->arrayNavigation();
		if(empty($this->childLookup))
			$this->childLookup = (array)$this->childLookup1 + (array)$this->childLookup2;	
		foreach($this->childLookup as $key => $value) {
			if($value == $str)
				$results[] = $key;
		}
		$each = '';
		if(!empty($results)) {
			foreach($results as $value) {
				if($GLOBALS['cleanUrls'] == "Enabled") {
					if(SIMPLE_CLEAN_URLS)
						$url = THEME_URL.$this->idLookup($value, false, true);
					else
						$url = THEME_URL.$value."/".$this->idLookup($value, false, true);
				}
				else {
					$url = THEME_URL."?page=".$value;					
				}
				$each .= sprintf($b, $this->idLookup($value, false, false), $url);
			}
		}
		else {
			$each = $c;
		}
		return sprintf($a, $each);
	}
	public function optionListFromArray($arr, $pre, $selected = "", $indent=0, $mother_run=true, $nameInValue = 0){
		$GLOBALS['cleanUrls'] = $this->getSetting('Clean Urls');
		foreach($arr as $k=>$v){
			// skip the baseval thingy. Not a real node.
			if($k == "__base_val") continue;
			
			if($k == "id" || $k == 'menutitle') continue;
			// determine the real value of this node.
			$show_val = ( is_array($v) ? $v["__base_val"] : $v );
	 
			if($k == "children") {
				$return .= $this->optionListFromArray($v, $pre, $selected, ($indent), false, $nameInValue);			
			}
			else {
				// show the actual node
				if($nameInValue == 1) {
					if($GLOBALS['cleanUrls'] == "Enabled") {
					if(SIMPLE_CLEAN_URLS)
						$url = THEME_URL.$this->make_clean_url($v['menutitle']);
					else
						$url = THEME_URL.$v['id']."/".$this->make_clean_url($v['menutitle']);
						$return .= "\t".str_repeat("\t", $indent)."<option value='$url'";
					}
					else {
						$return .= "\t".str_repeat("\t", $indent)."<option value='".THEME_URL."?page=".$v['id']."'";					
					}
				}
				else {
					$return .= "\t".str_repeat("\t", $indent)."<option value='".$pre.$v['id']."'";
				}
				if($selected != "") {
					if($selected == $v['id']) {
						$return .= " selected='selected'";
					}
				}
				$return .= ">".str_repeat("&#8212; ", $indent).stripslashes(stripslashes(stripslashes($v['menutitle'])))."</option>\n";
		 
				if(is_array($v)){
					// this is what makes it recursive, rerun for childs
					$return .= $this->optionListFromArray($v, $pre, $selected, ($indent+1), false, $nameInValue);
				}
			}
		}
		return $return;
	}
	public function buildNavArray($oneline = false) {
		return $this->arrayNavigation($oneline);
	}
	public function navigation (
		$root = "\n<ul id='ul-navigation'>\n%s\n</ul>\n",
		$child = "\n<ul class='ul-sub-navigation'>\n%s\n</ul>\n",
		$item = "\n\t<li><a href='%2\$s'>%1\$s</a></li>",
		$itemSelected = "\n\t<li class='selected'><a href='%2\$s'>%1\$s</a></li>",
		$itemHasChild = "\n\t<li><a href='%2\$s'>%1\$s</a>%3\$s</li>",
		$itemHasChildSelected = "\n\t<li class='selected'><a href='%2\$s'>%1\$s</a>%3\$s</li>",
		$isChild = false,
		$inputArray = array()
	) {
		if($this->navigation !== false && $isChild == false)
			$this->navigation = '';
		$GLOBALS['cleanUrls'] = $this->getSetting('Clean Urls');
		$GLOBALS['pageid'] = $_GET['page'];
		
		if($inputArray == array()) {
			$inputArray = $this->buildNavArray();
		}
		$x = 0;
		$r = '';
		$url = '';
		$count = count($inputArray);
		foreach($inputArray as $k=>$v) {
			if(is_array($v['children'])) {
				$sk = stripslashes(stripslashes(stripslashes($v['menutitle'])));
				if($GLOBALS['cleanUrls'] == "Enabled") {
					if(SIMPLE_CLEAN_URLS)
						$url = THEME_URL.$this->make_clean_url($v['menutitle']);
					else
						$url = THEME_URL.$v['id']."/".$this->make_clean_url($v['menutitle']);
				}
				else {
					$url = THEME_URL."?page=".$v['id'];					
				}
				if($GLOBALS['pageid'] == $v['id']) {
					$children = $this->navigation($root, $child, $item, $itemSelected, $itemHasChild, $itemHasChildSelected, true,$v['children']);
					$r .= sprintf($itemHasChildSelected, $sk, $url, $children);	
				}
				else {
					$children = $this->navigation($root, $child, $item, $itemSelected, $itemHasChild, $itemHasChildSelected, true,$v['children']);
					$r .= sprintf($itemHasChild, $sk, $url, $children);	
				}
			}
			else {
				if($GLOBALS['cleanUrls'] == "Enabled") {
					if(SIMPLE_CLEAN_URLS)
						$url = THEME_URL.$this->make_clean_url($v['menutitle']);
					else
						$url = THEME_URL.$v['id']."/".$this->make_clean_url($v['menutitle']);
				}
				else {
					$url = THEME_URL."?page=".$v['id'];					
				}
				if($GLOBALS['pageid'] == $v['id']) {
					$r .= sprintf($itemSelected, stripslashes(stripslashes(stripslashes($v['menutitle']))), $url); 
				}
				else {
					$r .= sprintf($item, stripslashes(stripslashes(stripslashes($v['menutitle']))), $url); 				
				}
				$x++;
				if(ltrim($x, '0') == $count) {
					return sprintf($child, $r, '');
				}
			}
		}
		if($isChild == true) {
			return sprintf($child, $r);
		}
		else {
			$this->navigation .= sprintf($root, $r);
		}
		return $this->navigation;
	}
	public function secondary_navigation (
		$root = "\n<ul id='ul-secondary-navigation'>\n%s\n</ul>\n",
		$child = "\n<ul class='ul-sub-navigation'>\n%s\n</ul>\n",
		$item = "\n\t<li><a href='%2\$s'>%1\$s</a></li>",
		$itemSelected = "\n\t<li class='selected'><a href='%2\$s'>%1\$s</a></li>",
		$itemHasChild = "\n\t<li><a href='%2\$s'>%1\$s</a>%3\$s</li>",
		$itemHasChildSelected = "\n\t<li class='selected'><a href='%2\$s'>%1\$s</a>%3\$s</li>",
		$isChild = false,
		$inputArray = array()
	) {
		if($this->secondary_navigation !== false && $isChild == false)
			$this->secondary_navigation = '';
		$GLOBALS['cleanUrls'] = $this->getSetting('Clean Urls');
		$GLOBALS['pageid'] = $_GET['page'];
		
		if($inputArray == array()) {
			$inputArray = $this->arraySecondaryNavigation();
		}
		$x = 0;
		$r = '';
		$url = '';
		$count = count($inputArray);
		foreach($inputArray as $k=>$v) {
			if(is_array($v['children'])) {
				$sk = stripslashes(stripslashes(stripslashes($v['menutitle'])));
				if($GLOBALS['cleanUrls'] == "Enabled") {
					if(SIMPLE_CLEAN_URLS)
						$url = THEME_URL.$this->make_clean_url($v['menutitle']);
					else
						$url = THEME_URL.$v['id']."/".$this->make_clean_url($v['menutitle']);
				}
				else {
					$url = THEME_URL."?page=".$v['id'];					
				}
				if($GLOBALS['pageid'] == $v['id']) {
					$children = $this->secondary_navigation($root, $child, $item, $itemSelected, $itemHasChild, $itemHasChildSelected, true,$v['children']);
					$r .= sprintf($itemHasChildSelected, $sk, $url, $children);	
				}
				else {
					$children = $this->secondary_navigation($root, $child, $item, $itemSelected, $itemHasChild, $itemHasChildSelected, true,$v['children']);
					$r .= sprintf($itemHasChild, $sk, $url, $children);	
				}
			}
			else {
				if($GLOBALS['cleanUrls'] == "Enabled") {
					if(SIMPLE_CLEAN_URLS)
						$url = THEME_URL.$this->make_clean_url($v['menutitle']);
					else
						$url = THEME_URL.$v['id']."/".$this->make_clean_url($v['menutitle']);
				}
				else {
					$url = THEME_URL."?page=".$v['id'];					
				}
				if($GLOBALS['pageid'] == $v['id']) {
					$r .= sprintf($itemSelected, stripslashes(stripslashes(stripslashes($v['menutitle']))), $url); 
				}
				else {
					$r .= sprintf($item, stripslashes(stripslashes(stripslashes($v['menutitle']))), $url); 				
				}
				$x++;
				if(ltrim($x, '0') == $count) {
					return sprintf($child, $r, '');
				}
			}
		}
		if($isChild == true) {
			return sprintf($child, $r);
		}
		else {
			$this->secondary_navigation .= sprintf($root, $r);
		}
		return $this->secondary_navigation;
	}
	public function static_content ($editable, $default, $textOnly = '') {
		$GLOBALS['cleanUrls'] = $this->getSetting('Clean Urls');
		$GLOBALS['pageid'] = $_GET['page'];
		if(isset($this->staticContent[$editable])) {
			$rec['content'] = $this->staticContent[$editable]['content'];
		}
		else {
			$sql = "INSERT INTO ".DBTABLEPREFIX."content_template (name, content, template, textOnly) VALUES ('".sanitize_sql_string($editable)."', '".sanitize_sql_string($default)."', '".$this->getSetting('Theme')."', '".sanitize_sql_string($textOnly)."')";
			$run = $this->db_query($sql) or die($this->db->error());
			$rec['content'] = $default;
			$row[$editable] = array(
				'content' => stripslashes($default),
				'name' => $editable,
				'textOnly' => $textOnly
			);
			$this->staticContent[$editable] = $row[$editable];
		}
		$this->themeStaticContent[$editable] = $this->staticContent[$editable];
		$r = stripslashes(stripslashes(stripslashes($rec['content'])));
		return $r;
	}
	public function arr_diff($a1,$a2){
		$ar = array();
		foreach ($a2 as $k => $v) {
			if (!is_array($v)) {
				if ($v !== $a1[$k])
					$ar[$k] = $v;
			}else{
				if ($arr = $this->arr_diff($a1[$k], $a2[$k]))
					$ar[$k] = $arr;
			}
		}
		return $ar;
	}
	public function cleanStaticContentTable () {
		$deleteItems = array_diff_assoc((array) $this->staticContent, $this->themeStaticContent);
		foreach($deleteItems as $key => $value) {
			$sql = "DELETE FROM ".DBTABLEPREFIX."content_template WHERE id = '{$value['id']}'";
			$run = $this->db_query($sql) or die($this->db->error());
		}
	}
	public function buildNavigation () {
		
	}
}
?>